package com.frame.demo.rest.sign;


import com.outer.pack.Key;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by bingo on 2015/3/20.
 */
public class Signer {

    private String url;

    public String getSign(Map<String, String> params, String url) {
        this.url = url;
        String sortStr = sortParams(params);
        return getRealSign(sortStr, getUrl());
    }

    public String getUrl() {
        return url;
    }

    public String sortParams(Map<String, String> params) {
        TreeMap<String, String> newParams = new TreeMap<String, String>(params);
        StringBuilder sb = new StringBuilder();
        for (Entry<String, String> entry : newParams.entrySet()) {
            // 过滤无效参数
            String name = entry.getKey();
            String value = entry.getValue();
            if (!name.equals("sign") && value != null
                    && !value.trim().equals("")) {
                sb.append("&" + entry.getKey().toLowerCase() + "="
                        + entry.getValue());
            }
        }
        if (sb.toString().length() > 0)
            return sb.toString().substring(1);
        else
            return "";
    }


    public String getRealSign(String baseString, String url) {
        String urlSuffix = parserSignKeyFromUrl(url);
        String KEY = null;
        if (Key.getKeys().get(urlSuffix) != null) {
            KEY = Key.getKeys().get(urlSuffix);
        } else {
            KEY = Key.getKeys().get("common");
        }

        byte[] sigByte = null;
        try {

            //  if (url.contains(PUSH_STR) || url.contains(UPDATE_STR) || url.contains(LOGIN_STR) ||
            //          url.contains(VERIFICATION_CODE_STR) || url.contains(BIND_STR)||
            //         url.contains(COUPON_STR) || url.contains(COUPON_FUNCTION) || url.contains(CITY_LIST)
            //          || url.contains(LOCATE_CITY)) {
            sigByte = SHA1.HmacSHA1Encrypt(baseString, KEY);
            //   } else {
            //  sigByte = SHA1.HmacSHA1Encrypt(BackGroundTask.getInstance().getToken() + baseString, KEY);
            //   }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // HMAC-SHA1加密
        String sig = SHA1.Base64(sigByte);// BASE-64编码
        return MD5Util.get32MD5Str(sig).toUpperCase();
    }

    /**
     * getRealSignUseJS供js调用误改
     *
     * @param baseString
     * @return
     */
    public String getRealSignUseJS(String baseString) {
        String KEY = null;
//        if (getKeys().get(urlSuffix) != null) {
//            KEY = getKeys().get(urlSuffix);
//        } else {
        KEY = Key.getKeys().get("common");
//        }

        byte[] sigByte = null;
        try {

            //  if (url.contains(PUSH_STR) || url.contains(UPDATE_STR) || url.contains(LOGIN_STR) ||
            //          url.contains(VERIFICATION_CODE_STR) || url.contains(BIND_STR)||
            //         url.contains(COUPON_STR) || url.contains(COUPON_FUNCTION) || url.contains(CITY_LIST)
            //          || url.contains(LOCATE_CITY)) {
            sigByte = SHA1.HmacSHA1Encrypt(baseString, KEY);
            //   } else {
            //  sigByte = SHA1.HmacSHA1Encrypt(BackGroundTask.getInstance().getToken() + baseString, KEY);
            //   }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // HMAC-SHA1加密
        String sig = SHA1.Base64(sigByte);// BASE-64编码
        return MD5Util.get32MD5Str(sig).toUpperCase();
    }

    public String getRealSignUseJS(String baseString, String type) {


        String urlSuffix = parserSignKeyFromUrl(url);
        String KEY = null;
        if (Key.getKeys().get(urlSuffix) != null) {
            KEY = Key.getKeys().get(urlSuffix);
        } else {
            KEY = Key.getKeys().get("common");
        }

        byte[] sigByte = null;
        try {

//            if (url.contains(PUSH_STR) || url.contains(UPDATE_STR) || url.contains(LOGIN_STR) ||
//                    url.contains(VERIFICATION_CODE_STR) || url.contains(BIND_STR) ||
//                    url.contains(COUPON_STR) || url.contains(COUPON_FUNCTION) || url.contains(CITY_LIST)
//                    || url.contains(LOCATE_CITY)) {
//                sigByte = SHA1.HmacSHA1Encrypt(baseString, KEY);
//            } else {
                sigByte = SHA1.HmacSHA1Encrypt("token" + baseString, KEY);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // HMAC-SHA1加密
        String sig = SHA1.Base64(sigByte);// BASE-64编码
        return MD5Util.get32MD5Str(sig).toUpperCase();


    }

    private String parserSignKeyFromUrl(String requestURI) {
        Matcher matcher = signPattern.matcher(requestURI);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            throw new IllegalArgumentException(requestURI
                    + " is not compliance with API");
        }
    }

    private final static Pattern signPattern = Pattern
            .compile("([^\\/]+)\\/[^\\/]+\\/?$");
}
